package com.boilerCloud.timer;

import java.util.List;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javax.annotation.Resource;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.boilerCloud.dto.device.DeviceInfo;
import com.boilerCloud.service.device.IDeviceService;
import com.fbox.Main;

@Configuration          //证明这个类是一个配置文件  
@EnableScheduling       //打开quartz定时器总开关  
public class Timer {  
	@Resource
	private IDeviceService deviceService;
	@Scheduled(cron = "0 0/5 * * * *")  
	public void timer(){  
	    //获取当前时间  
	    LocalDateTime localDateTime =LocalDateTime.now();  
	    System.out.println("当前时间为:" + localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));  
	    List<String> boxIds = deviceService.qryBoxIds();
	    for (int i = 0; i < boxIds.size(); i++) {
	    	JSONObject json = Main.getBoxInfo(boxIds.get(i));
			if(json != null){			
				String box_id =json.getString("uid");
				if(box_id == null){
					box_id = json.getJSONObject("box").getString("uid");
				}
				int state = json.getJSONObject("box").getJSONObject("commServer").getIntValue("state");
				deviceService.updateState(state,box_id);
			}
		}
	}  
	
	
	@Scheduled(cron = "0 0/1 * * * *")  
	public void timer1(){  
	    //获取当前时间  
		try {
	    LocalDateTime localDateTime =LocalDateTime.now();  
	    System.out.println("当前时间为:" + localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));  
	    List<DeviceInfo> boxs = deviceService.qrydeviceBoxIds();
		
	    DeviceInfo box = null;
	    long time = System.currentTimeMillis();
	    for (int i = 0; i < boxs.size(); i++) {
	    	box = boxs.get(i);
	    	JSONArray array = Main.getAlarmRecord(box.getBoxId(),box.getQueryTime(),time);
	    	deviceService.addWarnInfo(array,box.getId());
			
	    	deviceService.updateQueryTime(time, box.getId());
		}
	    
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}  
}  